package com.hxy.health.platform.controller;

import com.hxy.health.platform.common.Const;
import com.hxy.health.platform.common.ServerResponse;
import com.hxy.health.platform.pojo.User;
import com.hxy.health.platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 注册信息填写
     */
    @RequestMapping(value = "user/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse userRegister(User user) {
        // 先去数据库校验邮箱是否可以使用
        int status = userService.verifyEmail(user.getEmail());
        if (status > 0) {
            return ServerResponse.createByErrorMessage("邮箱已经被占用!");
        }
        // 写入数据库
        int result = userService.addUser(user);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("注册成功，请前去登录！");
        }
        return ServerResponse.createByErrorMessage("注册失败，请重试！");

    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "user/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        // 获取上一个路径
        String loginBackUrl=request.getHeader("Referer").toString();
        request.getSession(true).setAttribute(Const.CURRENT_USER, user);
        User u = userService.userLogin(user);
        if (u == null) {
            return ServerResponse.createByErrorMessage("用户账户名或者密码错误!");
        }
        return ServerResponse.createBySuccess("登录成功",loginBackUrl);
    }
}
